﻿using ClosedXML.Excel;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Implement;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.DepartmentCommand;
using D.Medicalcare.Write.API.Application.Commands.ReserInstrucCommand;
using D.Medicalcare.Write.API.Application.Handlers.ReserInstrucHarder;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace D.Medicalcare.Write.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ReserInstrucController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IBaseRepository<Physicalexamination> repository;

        public ReserInstrucController(IMediator mediator, IBaseRepository<Physicalexamination> repository)
        {
            this.mediator = mediator;
            this.repository = repository;
        }


        /// <summary>
        /// 预约须知新增
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> AddReserInstruc(AddReserInstrucCommand request)
        {
            return await mediator.Send(request);

        }






        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories2(IFormFile file)
        {
            APIResult<int> result = new APIResult<int>();

            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<Physicalexamination> inventoriesList = new List<Physicalexamination>();

                        foreach (var row in rows)
                        {
                            var inventory = new Physicalexamination();

                            // 尝试解析日期
                        

                            inventory.PatientId = row.Cell(1).GetValue<int>();
                            inventory.Hospital = row.Cell(2).GetValue<string>();
                            inventory.Address = row.Cell(3).GetValue<string>();
                            inventory.Department = row.Cell(4).GetValue<string>();
                            string dateStr = row.Cell(5).GetValue<string>();
                            if (DateTime.TryParse(dateStr, out DateTime PhysicalTime))
                            {
                                inventory.PhysicalTime = PhysicalTime;
                            }
                            else
                            {
                                result.Code = APIEnum.Failed;
                                result.Msg = $"导入失败，第 {row.RowNumber()} 行的日期格式错误：{dateStr}";
                                return StatusCode(500, result);
                            }
                            inventory.WaitingTime = row.Cell(6).GetValue<string>();
                            inventory.HealthCheckPackageId = row.Cell(7).GetValue<int>();
                            inventory.Medicalexaminationfee = row.Cell(8).GetValue<double>();
                            string dateStr2 = row.Cell(9).GetValue<string>();
                            if (DateTime.TryParse(dateStr2, out DateTime bookingTime))
                            {
                                inventory.bookingTime = bookingTime;
                            }
                            else
                            {
                                result.Code = APIEnum.Failed;
                                result.Msg = $"导入失败，第 {row.RowNumber()} 行的日期格式错误：{dateStr}";
                                return StatusCode(500, result);
                            }
                            inventory.State = row.Cell(10).GetValue<string>();
                            inventory.Remark = row.Cell(11).GetValue<string>();
                            inventory.IsDeleted = row.Cell(12).GetValue<bool>();
                            // 添加到要插入的列表中
                            inventoriesList.Add(inventory);
                        }

                        // 将数据批量插入数据库
                        await repository.AddRangeAsync(inventoriesList);

                        result.Code = APIEnum.Success;
                        result.Msg = "导入成功";
                        result.Data = inventoriesList.Count;
                    }
                }
            }
            catch (FormatException ex)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "导入失败，Excel 文件中数据格式错误：" + ex.Message;
                return StatusCode(500, result);
            }

            return Ok(result);
        }




    }
}
